<template>
  <div>
    <el-form @submit.native.prevent="addUser">
      <el-input v-model="form.userId" placeholder="用户ID"/>
      <el-input v-model="form.keyword" placeholder="密码"/>
      <el-button type="primary" @click="addUser">添加</el-button>
    </el-form>
    <el-table :data="records">
      <el-table-column prop="userId" label="用户ID"/>
      <el-table-column prop="keyword" label="密码"/>
      <el-table-column prop="createdTime" label="添加时间"/>
      <el-table-column prop="_class" label="路径"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button @click="deleteUser(scope.row.userId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <el-button type="primary" @click="navigateToPage">跳转到目标页</el-button>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
const form = ref({ userId: '', keyword: '' })
const records = ref([])

import { useRouter } from 'vue-router';

const router = useRouter();

const navigateToPage = () => {
  // 简单跳转
  router.push('/min');
}

const fetchRecords = async () => {
  const res = await axios.get('/user/list')
  console.log('获取到的数据:', res.data)
  console.log('第一条数据的字段:', Object.keys(res.data[0] || {}))
  records.value = res.data
}
const addUser = async () => {
  await axios.post('/user/add', form.value)
  fetchRecords()
}
const deleteUser = async (userId) => {
  console.log('删除用户ID:', userId)
  console.log('用户ID类型:', typeof userId)
  
  if (!userId || userId === 'undefined' || userId === '') {
    alert('用户ID不能为空，无法删除')
    return
  }
  
  try {
    await axios.delete('/user/delete/' + userId)
    console.log('删除成功')
    await fetchRecords()
  } catch (error) {
    console.error('删除失败:', error)
  }
}
onMounted(fetchRecords)
</script>